/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.component.cells;

import cn.ac.nercis.pes.common.constant.common.BaseConstants;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import org.apache.commons.lang3.StringUtils;

import java.util.stream.Stream;

/**
 * 弹出框单元格
 * @author zpy
 * @version 1.0.0
 */
public class DialogTableCell<S, T> extends TableCell<S, T> {
    private final String cellStyleCss;
    private final EventHandler<? super ActionEvent> openDialogEvent;

    public DialogTableCell(EventHandler<? super ActionEvent> openDialogEvent){
        this("",openDialogEvent);
    }

    public DialogTableCell(String cellStyleCss,EventHandler<? super ActionEvent> openDialogEvent){
        this.cellStyleCss = cellStyleCss;
        this.openDialogEvent = openDialogEvent;
        if(StringUtils.isNotBlank(cellStyleCss)){
            getStyleClass().add(cellStyleCss);
        }
    }

    @Override
    protected void updateItem(T item, boolean empty) {
        super.updateItem(item, empty);
        if (empty) {
            setText(null);
            setGraphic(null);
        } else {
            String content = getValue() == null ? "" : String.valueOf(getValue());
            VBox vBox = new VBox();
            vBox.getStyleClass().add(StringUtils.isBlank(cellStyleCss)?"v-box":cellStyleCss);
            Stream.of(content.split(BaseConstants.REGEX_WRAP_TEXT_SPLIT))
                    .filter(StringUtils::isNotBlank)
                    .forEach(value->{
                        Label label = new Label(value);
                        label.setWrapText(true);
                        vBox.getChildren().add(label);
                    });
            vBox.setOnMouseClicked(this::onMouseClick);
            setGraphic(vBox);
        }
    }

    private void onMouseClick(MouseEvent me){
        openDialogEvent.handle(new ActionEvent());
    }

    protected Object getValue() {
        return getItem();
    }
}